"""
__author__='fanxn19000'
__date__='2018/10/23'
用于生成token，以及管理用户会话
"""
from trainUser.models import UserToken
from django.shortcuts import render
from django.core import signing
import hashlib
import time
import datetime

# 登录失效时间
expiryTime = 30

class TokenUtil():

    def __init__(self):
        self.HEADER = {'typ': 'JWP', 'alg': 'default'}
        self.KEY = 'EPG_TEST_TOOLS'
        self.SALT = 'www.HUNDSUN.com'

    def encrypt(self,obj):
        """加密"""
        value = signing.dumps(obj, key=self.KEY, salt=self.SALT)
        value = signing.b64_encode(value.encode()).decode()
        return value

    def decrypt(self,src):
        """解密"""
        src = signing.b64_decode(src.encode()).decode()
        raw = signing.loads(src, key=self.KEY, salt=self.SALT)
        print(type(raw))
        return raw


    def generateUserToken(self,realm_account):
        header = self.encrypt(self.HEADER)
        payload = {"realm_account": realm_account, "iat": time.time()}
        payload = self.encrypt(payload)

        md5 = hashlib.md5()
        md5.update(("%s.%s" % (header, payload)).encode())
        signature = md5.hexdigest()
        token = "%s.%s.%s" % (header, payload, signature)
        return token

    def getToken(self,realm_account):
        token = UserToken.objects.filter(realm_account=realm_account)
        if token:
            token = token[0].user_token
            UserToken.objects.filter(realm_account=realm_account).update(login_day=datetime.datetime.now())
        else:
            token = self.generateUserToken(realm_account)
            UserToken.objects.create(realm_account=realm_account,
                                     login_day=datetime.datetime.now(),
                                     user_token = token)
        return token


    def getRealmAccount(self,token):
        payload = str(token).split('.')[1]
        payload = self.decrypt(payload)
        return payload["realm_account"]

    def updateUserToken(self,token):
        UserToken.objects.filter(user_token=token).update(login_day=datetime.datetime.now())

    def tokenOut(self,token):
        UserToken.objects.filter(user_token=token).delete()


    def isLogin(self,token):

        if len(str(token).strip()) == 0:
            return False
        else:
            user_token = UserToken.objects.filter(user_token=token)
            if user_token:
                login_day = user_token.all()[0].login_day
                if (datetime.datetime.now() - login_day).seconds/60 > expiryTime:
                    return False
                else:
                    return True
            else:
                return False
